package team.fourth.combat.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import team.fourth.combat.commen.entity.Result;
import team.fourth.combat.commen.utils.POIUtils;
import team.fourth.combat.pojo.OrderSetting;
import team.fourth.combat.service.OrderSettingService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/ordersetting")
@RestController
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @RequestMapping("/setNumberByDate")
    public Result setNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.setNumberByDate(orderSetting);
        return Result.success("");
    }

    /**
     * Integer（带缓存） int 有啥区别
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            //使用poiutil解析excel
            List<String[]> datas = POIUtils.readExcel(excelFile);

            List<OrderSetting> orderSettings = new ArrayList<>();
            //把List<String[]> datas  转换成 List<OrderSetting> orderSettings
            if(CollectionUtil.isNotEmpty(datas)){
                for (String[] row : datas) {
                    if(row.length != 2){
                        continue;
                    }
                    String dateStr = row[0];
                    String numberStr = row[1];
                    if(StringUtils.isEmpty(dateStr) || StringUtils.isEmpty(numberStr)){
                        continue;
                    }
                    OrderSetting orderSetting = new OrderSetting(DateUtil.parse(dateStr,"yyyy/MM/dd"),Integer.valueOf(numberStr));
                    orderSettings.add(orderSetting);
                }
            }
            //保存
            orderSettingService.batchSave(orderSettings);
            return Result.success("");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("批量导入失败，请检查Excel");
        }
    }


    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestBody Map map){
        String date =  (String)map.get("mouth");
        // {"date":22,"mouth":0,"number":300,"reservations":300,}
        List<OrderSetting> maps = orderSettingService.getOrderSettingByMonth(date);
        return Result.success("",maps);
    }
}
